package com.alm.handle.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alm.common.core.redis.RedisCache;
import com.alm.entity.DevMeterCurrent;
import com.alm.handle.core.domain.entity.SysDevCurrentData;
import com.alm.handle.core.domain.entity.SysDevCurrentData_s;
import com.alm.handle.core.domain.entity.rs.SysDevCurrentDataRS;
import com.alm.handle.core.domain.entity.vo.CurrentVo;
import com.alm.handle.mapper.SysDevCurrentDataMapper;
import com.alm.handle.mapper.SysDevCurrentData_sMapper;
import com.alm.handle.service.ISysDevCurrentDataService;
import com.alm.handle.service.ISysDevCurrentData_sService;
import com.alm.handle.util.ELeCurrentUtil;
import com.alm.handle.util.SoketEleKey;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.util.StringUtil;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STBorderId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SysDevCurrentData_sServiceImpl implements ISysDevCurrentData_sService {
    @Resource
    SysDevCurrentData_sMapper data_sMapper;
    @Autowired
    ISysDevCurrentDataService dataService;
    @Autowired
    RedisCache redisCache;
    @Override
    public void upDevCurrentData(DevMeterCurrent devMeterCurrent) {
        UpdateWrapper queryWrapper=new UpdateWrapper();
        queryWrapper.eq("devid",devMeterCurrent.getDeviceId());
        queryWrapper.eq("line_no",devMeterCurrent.getMsgNo());
        queryWrapper.setSql(" up_version = up_version + 1 ");
        SysDevCurrentData_s currentData=new SysDevCurrentData_s();
        currentData.setDevid(devMeterCurrent.getDeviceId());
        currentData.setLineNo(devMeterCurrent.getMsgNo());
        currentData.setRelayStatus(devMeterCurrent.getRelayStatus());
        currentData.setWorkStatus(devMeterCurrent.getWorkStatus());
        currentData.setElectricCurrent(new BigDecimal(devMeterCurrent.getElectricCurrent()));
        currentData.setPowerFactor(new BigDecimal(devMeterCurrent.getPowerFactor()));
        currentData.setEnergy(new BigDecimal(devMeterCurrent.getEnergy()));
        currentData.setActivePower(new BigDecimal(devMeterCurrent.getActivePower()));
        int up=  data_sMapper.update(currentData,queryWrapper);
        if(up<=0){
            currentData.setUpVersion(1);
            data_sMapper.insert(currentData);
        }
    }

    @Override
    public void upDateCurrent_s(DevMeterCurrent current) {
        current.calculate();
        String redisDataKey= SoketEleKey.ELES_DATA+current.getDeviceId();
        String redisData=redisCache.getCacheObject(redisDataKey);
        Map map;
        CurrentVo currentVo;
        currentVo= ELeCurrentUtil.replaceData(current);
        if(!StringUtil.isEmpty(redisData)){
            map= JSON.parseObject(redisData,Map.class);
            JSONObject oldData= (JSONObject) map.get(currentVo.getLineNo());
            if(oldData!=null){
                CurrentVo oldcurrentVo=JSON.parseObject(oldData.toJSONString(),CurrentVo.class);
                currentVo=ELeCurrentUtil.resetData(oldcurrentVo,currentVo);
            }
        }else {
            map=new HashMap();
        }
        map.put(currentVo.getLineNo(),currentVo);
        currentVo.setNetWorkType(1);
        redisCache.setCacheObject(redisDataKey,JSON.toJSONString(map), 3, TimeUnit.MINUTES);
    }
    /**
     * 计算多路总数据
     * @param
     */
    @Override
    public void upSumDataCurrent( DevMeterCurrent devMeterCurrent) {
        devMeterCurrent.calculate();
        String redisDataKey= SoketEleKey.ELES_DATA+devMeterCurrent.getDeviceId();
        String redisData=redisCache.getCacheObject(redisDataKey);
        if(!StringUtil.isEmpty(redisData)){
            Map map= JSON.parseObject(redisData,Map.class);
            Double sumCurrent= 0.0;
            Double powerFactor= 0.0;
            Double energy= 0.0;
            Double activePower= 0.0;
            for(Object currentVo1:map.values()){
                JSONObject jsonObject=  (JSONObject) currentVo1;
                CurrentVo data=JSON.parseObject(jsonObject.toJSONString(),CurrentVo.class);
                sumCurrent+=data.getCurrent()==0?0:data.getCurrent();
                powerFactor+=data.getPowerFactor()==0?0:data.getPowerFactor();
                energy+=data.getEnergy()==0?0:data.getEnergy();
                activePower+=data.getActivePower()==0?0:data.getActivePower();
            }
            devMeterCurrent.setEnergy(energy);
            devMeterCurrent.setElectricCurrent(sumCurrent);
            devMeterCurrent.setActivePower(activePower);
            devMeterCurrent.setPowerFactor(powerFactor);
            dataService.upDateCurrent(devMeterCurrent);
        }
    }

    @Override
    public List<SysDevCurrentData_s> findByMac(String mac) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.orderBy(true,true,"line_no");
        queryWrapper.eq("devid",mac);
        List<SysDevCurrentData_s> list=data_sMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    public List<SysDevCurrentData_s> findByMacByData(String mac) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.orderBy(true,true,"line_no");
        queryWrapper.eq("devid",mac);
        List<SysDevCurrentData_s> list=data_sMapper.selectList(queryWrapper);
        if(list!=null&&list.size()>0){
            for (SysDevCurrentData_s data_s:list){
                replaceRealTime(data_s);
            }
        }
        return list;
    }

    private SysDevCurrentData_s replaceRealTime(SysDevCurrentData_s dataRS){
        String redisDataKey=SoketEleKey.ELES_DATA+dataRS.getDevid();
        if(redisCache.hasKey(redisDataKey)){
            String redisData=redisCache.getCacheObject(redisDataKey);
            if(redisData!=null&&!redisData.equals("")){
                Map map= JSON.parseObject(redisData,Map.class);
                JSONObject jsonObject=  (JSONObject) map.get(dataRS.getLineNo());
                CurrentVo currentVo=JSON.parseObject(jsonObject.toJSONString(),CurrentVo.class);
                dataRS.setRelayStatus(currentVo.getRelayStatus());
                dataRS.setWorkStatus(currentVo.getWorkStatus());
                dataRS.setElectricCurrent(currentVo.getCurrent()!=null?new BigDecimal(currentVo.getCurrent()).setScale(4,BigDecimal.ROUND_CEILING):new BigDecimal(0));
                dataRS.setPowerFactor(currentVo.getPowerFactor()!=null?new BigDecimal(currentVo.getPowerFactor()).setScale(4,BigDecimal.ROUND_CEILING):new BigDecimal(0));
                dataRS.setEnergy(currentVo.getEnergy()!=null?new BigDecimal(currentVo.getEnergy()).setScale(4,BigDecimal.ROUND_CEILING):new BigDecimal(0));
                dataRS.setActivePower(currentVo.getActivePower()!=null?new BigDecimal(currentVo.getActivePower()).setScale(4,BigDecimal.ROUND_CEILING):new BigDecimal(0));
            }
        }
        return dataRS;
    }
}
